package com.hspedu.newData.dmsxl.树.公共祖先;

import com.hspedu.newData.dmsxl.ds.TreeNode;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-19 
 * @Version: 1.0
 */

public class LC236二叉树的最近公共祖先 {

    // todo 递归
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        if (root == null || root == p || root == q){
            return root;
        }

        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);

        if (left == null && right == null){
            return null;
        } else if (left == null && right != null) {
            return right;
        } else if (left != null && right == null) {
            return left;
        }else {
            return root;
        }
    }

    // todo 迭代


}
